package cn.iocoder.boot.utils;


import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class HmacSha1Util {

    public static String calculateHmacSha1(String data, String key)
            throws NoSuchAlgorithmException, InvalidKeyException {
        String algorithm = "HmacSHA1";

        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(secretKeySpec);

        byte[] rawHmac = mac.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(rawHmac);

        // 如果需要十六进制字符串而不是Base64，可以使用下面的代码：
        // return bytesToHex(rawHmac);
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        try {
            String data = "POST&https%3A%2F%2Fapi.tme,eu%2FProducts%2FGetStocks.ison&Lanquage%3DEN%26SymbolList%255B0%255D%3D1N4007%26SymbolList%255B1%255D%3D1%252F4W1.1M%26Token%3Da94a8fe5ccb19ba61c4c0873d391e987982fbbd3";
            String key = "test";

            String signature = calculateHmacSha1(data, key);
            System.out.println("HMAC-SHA1 Signature (Base64): " + signature);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
